package com.leyou.page.service;

import com.sun.org.apache.bcel.internal.generic.IFNULL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;

/**
 * @author 岩冰
 * @version 1.0
 * @date:2018/10/15
 */
@Service
public class FileService {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private TemplateEngine templateEngine;

    @Value("${ly.thymeleaf.destPath}")
    private String destPath;

    public void createHtml(Long id) throws Exception {
        Context context = new Context();
        context.setVariables(this.goodsService.loadModel(id));

        //创建输出流
        File temp = new File(id + ".html");
        File dist=createPath(id);
        //备份源文件
        File bak = new File(id + "_bak.html");

        try (PrintWriter writer = new PrintWriter(temp, "utf-8")) {
            templateEngine.process("item", context, writer);
            if (dist.exists()) {
                dist.renameTo(bak);
            }
            FileCopyUtils.copy(temp, dist);
            bak.delete();
        } catch (Exception e) {
            bak.renameTo(dist);
            throw new Exception(e);
        }finally {
            if (temp.exists()) {
                temp.delete();
            }
        }
    }

    public Boolean exists(Long id) {
        return this.createPath(id).exists();
    }
    private File createPath(Long id) {
        if (id==null) {
            return null;
        }
        File dest = new File(this.destPath);
        if (!dest.exists()) {
            dest.mkdirs();
        }
        return new File(dest, id + ".html");
    }

    public void deleteHtml(Long id) {
        File file = new File(this.destPath, id + ".html");
        file.deleteOnExit();
    }
}
